import Ajax, {
    AxiosRequestConfig
} from 'axios';

import {
    UploadImageError
} from './const';

import {
    UploadVideoPara
} from './types';

import * as Env from './../env';
import Auth from './../env/auth';

const Instance = Ajax.create({
    headers: {
        [`Content-Type`]: `multipart/form-data`
    }
})

Instance.interceptors.request.use(async (
    config: AxiosRequestConfig
) => {
    const {
        headers
    } = config;
    headers[`Authorization`] = Auth.upload;
    config.baseURL = await Env.uploadBaseUrl();
    return config;
})

Instance.interceptors.response.use(res => {
    const {
        data
    } = res;
    const {
        code
    } = data;
    if (code === 200) {
        return data.data;
    }
    return Promise.reject(UploadImageError)
},() => (
    Promise.reject(UploadImageError)
))

const checkHttp = (uri: string) => (
    /http/.test(uri)
)

//图片上传
export const image = async (uri = ``) => {
    const fields: any = {};
    const formData = new FormData();
    if (checkHttp(uri)) {
        fields[`filename`] = uri;
    }
    else {
        fields[`file`] = {
            uri: uri,
            name: `${Date.now()}.jpg`,
            type: `multipart/form-data`
        }
    }
    Object.keys(fields).forEach(key => (
        formData.append(key, fields[key])
    ))
    return Instance.post(`/photo`, formData)
}

//视频上传
export const video = async (uri: string, data: UploadVideoPara) => {
    const formData = new FormData();
    const file = {
        uri: uri,
        name: `${Date.now()}.mp4`,
        type: `multipart/form-data`
    }
    const fields:any = {
        ...data,
        file: file
    }
    Object.keys(fields).forEach(key => (
        formData.append(key, fields[key])
    ))
    return Instance.post(`/video`, formData);
}




